<template>
    <div class="carrier-chart-container">
        <!-- 中间主体：饼图 + 信息 -->
        <div class="chart-info-wrapper">
            <!-- 左：饼图 -->
            <div ref="chartRef" class="chart"></div>

            <!-- 右：文字信息 -->
            <div class="info-list">
                <div
                        v-for="(item, index) in visibleData"
                        :key="index"
                        class="info-item"
                >
                    <div class="info-left">
            <span
                    class="color-dot"
                    :style="{ backgroundColor: getColor(item, index) }"
            ></span>
                        <span class="name">{{ item.name }}</span>
                    </div>
                    <div class="info-right">
                        <div class="value">¥{{formatToWan(item.value)}}</div>
                        <div
                                class="growth"
                                :class="{ up: item.growth > 0, down: item.growth < 0 }"
                        >
                            较上周期
                            <span>{{ item.growth > 0 ? "↑" : item.growth < 0 ? "↓" : "" }}</span>
                            {{ Math.abs(item.growth) }}%
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- ✅ 底部按钮 -->
        <div class="legend-toggle">
            <el-button
                    v-for="(item, index) in chartData"
                    :key="index"
                    size="small"
                    @click="toggleItem(item.name)"
                    :style="{
          backgroundColor: item.visible ? getColor(item, index) : '#fff',
          color: item.visible ? '#fff' : getColor(item, index),
          borderColor: getColor(item, index)
        }"
            >
                {{ item.name }}
            </el-button>
        </div>
    </div>
</template>

<script setup>
    import {ref, computed, onMounted, onBeforeUnmount, nextTick, isRef,watch} from "vue";
    import * as echarts from "echarts";
    import {formatToWan} from '../../utils/number.js'

    const props = defineProps({
        chartData: {type: [Array, Object], default: () => []}
    })
    // <!-- 使用计算属性 chartData，确保它始终反映 props.sections[0].items 的变化 -->
    // // ✅ 统一转成 ref，保证 chartData.value 存在
    const chartData = computed(() => {
        return isRef(props.chartData) ? props.chartData.value : props.chartData;
    });

    // /* ✅ 数据 + 颜色 */
    // const chartData = ref([
    //     { name: "直播", value: 15368016.39, growth: -45.08, visible: true },
    //     { name: "商品卡", value: 4209505.64, growth: -34.89, visible: true},
    //     { name: "短视频", value: 935730.81, growth: 6.35, visible: true },
    //     { name: "图文", value: 50820.34, growth: 43.56, visible: true },
    //     { name: "其他", value: 167115.65, growth: -23.15, visible: true},
    // ]);

    const colorList = ["#ffc000", "#1d69ff", "#5eddd8", "#70ad47", "#ed7d31"];
    // const getColor = (item, index) => item.color || colorList[index % colorList.length];
    const getColor = (item, index) => {
        const color = item.color || colorList[index % colorList.length];
        return color;
    };
    const chartRef = ref(null);
    let chartInstance = null;
    let resizeObserver = null;


    const visibleData = computed(() => {
        const arr = chartData?.value || []
        return Array.isArray(arr) ? arr.filter(d => d.visible) : []
    })

    const toggleItem = (name) => {
        const item = chartData.value.find((i) => i.name === name);
        item.visible = !item.visible;
        renderChart();
    };

    /* ✅ 渲染图表 */
    function renderChart() {
        if (!chartRef.value) return;
        const width = chartRef.value.clientWidth;
        const height = chartRef.value.clientHeight;
        if (!width || !height) return;

        if (!chartInstance) chartInstance = echarts.init(chartRef.value);

        chartInstance.setOption({
            tooltip: {trigger: "item", formatter: "{b}<br/>¥{c}<br/>占比 {d}%"},
            series: [
                {
                    name: "载体分布",
                    type: "pie",
                    radius: ["55%", "75%"],
                    center: ["50%", "50%"],
                    label: {
                        show: true,
                        position: "center",
                        formatter: "载体分布",
                        fontSize: 16,
                        fontWeight: "bold",
                    },
                    labelLine: {show: false},
                    itemStyle: {
                        // color: (params) =>getColor(visibleData.value[params.dataIndex], params.dataIndex),
                        color: (params) => {
                            // console.log("ECharts params：", params);
                            const index = params.dataIndex;
                            const item = visibleData.value[index];
                            const color = getColor(item, index);
                            // console.log(`[颜色调试] ${item.name} (${index}) → ${color}`);
                            return color;
                        },
                    },
                    data: visibleData.value,
                },
            ],
        });
    }

    /* ✅ 生命周期 */
    onMounted(async () => {
        await nextTick();
        resizeObserver = new ResizeObserver(() => renderChart());
        resizeObserver.observe(chartRef.value);
        renderChart();
    });



    // 监听 chartData 的变化并更新图表
    watch(chartData, () => {
        renderChart();
    }, { deep: true });

    // 清理工作
    onBeforeUnmount(() => {
        resizeObserver?.disconnect();
        chartInstance?.dispose();
    });

    /* ✅ 格式化数字 */
    // const formatNumber = (num) =>
    //     num.toLocaleString("zh-CN", { minimumFractionDigits: 2 });


</script>

<style scoped>
    .carrier-chart-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 100%;
        margin-top: 20px;
    }

    /* ✅ 主体布局：PC 左右，移动上下 */
    .chart-info-wrapper {
        display: flex;
        align-items: center; /* ✅ 垂直居中 */
        justify-content: center;
        gap: 40px;
        width: 100%;
        flex-wrap: wrap;
    }

    /* 饼图 */
    .chart {
        width: 340px;
        height: 280px;
        flex-shrink: 0;
    }

    /* 信息列表 */
    .info-list {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 14px 60px;
        min-width: 50%;
    }

    /* 移动端改为竖向 */
    @media (max-width: 768px) {
        .chart-info-wrapper {
            flex-direction: column;
            align-items: center;
        }

        .chart {
            width: 260px;
            height: 220px;
        }

        .info-list {
            grid-template-columns: 1fr;
            text-align: center;
            min-width: 80%;
        }
    }

    /* 信息卡片 */
    .info-item {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
    }

    .info-left {
        display: flex;
        align-items: center;
        gap: 6px;
        font-weight: bold;
        color: #333;
    }

    .color-dot {
        width: 10px;
        height: 10px;
        border-radius: 50%;
    }

    .info-right {
        text-align: right;
    }

    .value {
        font-weight: bold;
        font-size: 15px;
        color: #000;
    }

    .growth {
        font-size: 13px;
        margin-top: 2px;
    }

    .growth.up {
        color: #dc3545;
    }

    .growth.down {
        color: #28a745;
    }

    /* 底部按钮区 */
    .legend-toggle {
        margin-top: 20px;
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        gap: 10px;
    }

    .legend-toggle .el-button {
        border-radius: 6px;
        padding: 6px 12px;
        font-size: 14px;
        font-weight: 600;
    }
</style>
